# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:

from MysqlTools import MysqlTools
import json

class Tools:

    def __init__(self, **kwargs):
        self.db = MysqlTools(db_config=kwargs.get("db_config"), type='dict', auto_commit=10000)
        self.d_db = MysqlTools(db_config=kwargs.get("dest_config"), type='dict', auto_commit=10000)
        self.src_table = kwargs.get("src_table")
        self.dest_table = kwargs.get("dest_table")

    def get_cid_years_dict(self):
        sql = '''select distinct `code`,`condition` from `cars_info_collection`'''
        data = self.db.select_all(sql)
        _dict = {i.get("code"): i.get("condition")[:8] for i in data}
        return _dict

    def run(self):
        cid_years_dict = self.get_cid_years_dict()
        start = 0
        step = 1000000
        while True:
            sql = 'select * from {} limit {}, {}'.format(self.src_table, start, step)
            all_sql_data = self.db.select_all(sql)
            start += step
            _len = len(all_sql_data)
            print(_len)
            for data in all_sql_data:
                v_year = data.get("year")
                v_cid = data.get("code")
                v_ex = json.loads(data.get("extra_info"))
                if int(v_year) < int(cid_years_dict.get(v_cid)):
                    data['year'] = str(cid_years_dict.get(v_cid))
                    for i in v_ex:
                        i['years'] = str(cid_years_dict.get(v_cid))
                    data['maindata'] = data['maindata'].replace(v_year, str(cid_years_dict.get(v_cid)))
                data['extra_info'] = json.dumps(v_ex)
                data['updatetime'] = 'now()'
                data['createtime'] = 'now()'
                insert_sql = self.d_db.get_insert_sql(self.dest_table, data)
                self.d_db.execute_sql(insert_sql)
            self.d_db.commit_sql()
            if _len < step:
                break
        self.db.commit_sql()


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    dest_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    src_table = 'cars_vin_info_years_err'
    dest_table = 'cars_vin_info'
    tools = Tools(db_config=db_config, dest_config=dest_config, src_table=src_table, dest_table=dest_table)
    tools.run()